<script setup>
import { ref, onMounted, watch } from 'vue'
import Lottie from './Lottie/index.vue'
import Animation from '../assets/Animation - 1712559820721.json'
import Animation1 from '../assets/Animation-1.json'

const a1 = ref(null)
const count = ref(0)
const likeFlag = ref(false)

const getAnimation = (animation) => {
  a1.value = animation
  if (a1.value) {
    a1.value.addEventListener('enterFrame', () => {
      // console.log(a1.value, '--a1.value--');
      if (a1.value.currentFrame >= 63) {
        // 当前帧
        a1.value.goToAndPlay(0, true) // 跳转到指定帧开始
      }
    })
    a1.value.addEventListener('complete', () => {
      console.log('播放完毕')
    })
  }
}
const play = () => {
  if (likeFlag.value) {
    a1.value.playSegments([31, 64], true) // 播放指定的片段，([开始帧，结束帧], 是否立即播放)
  } else {
    a1.value.playSegments([0, 30], true)
  }
  likeFlag.value = !likeFlag.value
  count.value++
}

// const likeClick = () => {
//   console.log('likeClick');
//   a1.value.setSpeed(2) // 设置播放速度
//   // a1.value.setDirection(-1) // 设置播放速度,不知道什么原因这里没有生效
//   a1.value.stop()
//   setTimeout(() => {
//     // a1.value.goToAndStop(31, true) // 跳到指定帧结束，第二个参数 isFrame 为是否基于帧模式还是时间，默认为 false
//     // a1.value.goToAndPlay(21, true) // 跳转到指定帧开始
//     a1.value.play();
//   }, 100); // 延迟100毫秒播放
//   const duration = a1.value.getDuration(true) // true 为帧， false 为秒
//   console.log(duration, '--duration--'); // 64帧 2.56秒
// }

// 监听鼠标滚动事件
let frame = 0
const maxFrame = 60 // 假设最大值为100
window.addEventListener('wheel', (event) => {
  console.log(event, '--event--')
  if (event.wheelDelta < 0) {
    frame += 10
    count.value++
  } else if (event.wheelDelta >= 149) {
    frame -= 10
    count.value--
  }
  if (frame >= maxFrame) {
    frame = 0 // 重置为0
  } else if (frame < 0) {
    frame = maxFrame // 重置为最大值
  }
  a1.value.goToAndStop(frame, true)
  console.log(frame, '--frame--')
})

onMounted(() => {})
</script>

<template>
  <div class="card">
    <div>
      <Lottie :animation-data="Animation" />
    </div>
    <div class="card-body">
      <Lottie
        class="a1"
        :animation-data="Animation1"
        :loop="false"
        :autoplay="true"
        @get-animation="getAnimation"
        @click="likeClick"
      />
      <button @click="play">Play</button>
      <div class="count">{{ count }}</div>
      <div class="info">测试内容</div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.card {
  display: flex;
  align-items: center;
  width: 700px;

  /* margin: 0 auto; */
  .card-body {
    position: relative;

    .info {
      position: absolute;
      left: 50%;
      top: 20%;
      transform: translate(-50%, -50%);
      color: rgb(255, 255, 255);
    }
  }
}
</style>
